from typing import *


class Solution:

    def maximumScoreAfterOperations(self, edges: List[List[int]],
                                    values: List[int]) -> int:
        n = len(values)
        nexts = [[] for _ in range(n)]
        for a, b in edges:
            nexts[a].append(b)
            nexts[b].append(a)

        def f(c, p):
            if len(nexts[c]) == 1 and p != -1:
                return [values[c], 0]
            tot, subt = 0, 0
            for next in nexts[c]:
                if next != p:
                    a, b = f(next, c)
                    tot += a
                    subt += b

            return [tot + values[c], max(tot, subt + values[c])]

        return f(0, -1)[1]
